package wcpackage.domain.entities;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * User: rabbit
 * Date: Jun 11, 2009
 * Time: 12:27:15 AM
 */
@javax.persistence.Entity
@Table(name = "users")
@SequenceGenerator(name = "users_id_seq", sequenceName = "users_id_seq", initialValue = 10)
@NamedQueries(
        @NamedQuery(name = "User.findByLoginAndPassword",
                query = "select user from User user " +
                        "where login = :login and password = :password")
)
public class User extends AbstractEntity<Long> {

    public static User GUEST_USER = new User("Gość", "");

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_id_seq")
    private Long id;

    @Column(nullable = false, name = "login")
    private String login;

    private String firstName;

    private String lastName;

    @Column(name = "password")
    private String password;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name = "users_roles", joinColumns =
    @JoinColumn(name = "users_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "roles_id", referencedColumnName = "id"))
    private List<Role> roles = new ArrayList<Role>();

    public User(String login, String password) {
        this.login = login;
        this.password = password;
    }

    public User() {
    }

    public User(User user) {
        login = user.login;
        firstName = user.firstName;
        lastName = user.lastName;
    }

    public void clearData() {
        login = "";
        firstName = "";
        lastName = "";
    }

    public boolean hasAccesRights(String accessRightsCode) {
        for (Role role : roles) {
            for (AccessRight accessRight : role.getAccessRights()) {
                if (accessRight.getCode().equals(accessRightsCode) || accessRight.getCode().equals("all")) {
                    return true;
                }
            }
        }
        return false;
    }

    public Long getId() {
        return id;
    }

    public IEntity<Long> setId(Long id) {
        this.id = id;
        return this;
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "login='" + login + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}
